@file:Suppress("NOTHING_TO_INLINE", "unused")

package com.xh.baselibrary.ex

import android.content.Context
import android.content.SharedPreferences as SP

/**
 * Note:
 *
 * @author sens 2019/9/26
 */
inline fun <reified T> SP.getValue(key: String): T? = all?.get(key) as? T?

inline fun SP.setValue(key: String, value: Int) {
    edit().apply { this.putInt(key, value) }.apply()
}

inline fun SP.setValue(key: String, value: Long) {
    edit().apply { this.putLong(key, value) }.apply()
}

inline fun SP.setValue(key: String, value: Float) {
    edit().apply { this.putFloat(key, value) }.apply()
}

inline fun SP.setValue(key: String, value: Boolean) {
    edit().apply { this.putBoolean(key, value) }.apply()
}

inline fun SP.setValue(key: String, value: String?) {
    edit().apply { this.putString(key, value) }.apply()
}

inline fun SP.setValue(key: String, value: Set<String>?) {
    edit().apply { this.putStringSet(key, value) }.apply()
}

inline fun SP.setValue(editor: SP.Editor.() -> Unit) {
    edit().apply { this.editor() }.apply()
}

inline fun SP.remove(key: String) = edit().remove(key).apply()

inline fun SP.clear() = edit().clear().apply()

inline val SP.size get() = all?.size ?: 0


inline fun Context.sp(name: String, mode: Int = Context.MODE_PRIVATE): SP {
    return this.getSharedPreferences(name, mode)
}

inline fun <reified T> Context.getSPValue(name: String, key: String, mode: Int = Context.MODE_PRIVATE): T? {
    return sp(name, mode).getValue<T>(key)
}

inline fun Context.setSPValue(name: String, key: String, value: Int, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, key: String, value: Long, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, key: String, value: Float, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, key: String, value: Boolean, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, key: String, value: String?, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, key: String, value: Set<String>?, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(key, value)
}

inline fun Context.setSPValue(name: String, editor: SP.Editor.() -> Unit, mode: Int = Context.MODE_PRIVATE) {
    return sp(name, mode).setValue(editor)
}

inline fun Context.spRemove(name: String, key: String, mode: Int = Context.MODE_PRIVATE) = sp(name, mode).remove(key)

inline fun Context.spClear(name: String, mode: Int = Context.MODE_PRIVATE) = sp(name, mode).clear()

inline fun Context.spSize(name: String, mode: Int = Context.MODE_PRIVATE) = sp(name, mode).size